import os
import random
import glob
import cv2
import math
import numpy as np
from numpy.matlib import repmat
from PIL import Image, ImageFilter, ImageEnhance


class AugmentBright():
    def __init__(self):
        self.a = 0

    def equalize_hist_3d(self, img):

        for item in range(0, img.shape[2]):
            img[:, :, item] = cv2.equalizeHist(img[:, :, item])

        return img

    def normalization_3d(self, img):

        for item in range(0, img.shape[2]):
            img[:, :, item] = (img[:, :, item] - np.min(img[:, :, item])) / (
                    np.max(img[:, :, item]) - np.min(img[:, :, item])) * 255

        return img

    def rotation_3d(self, img, angle):

        h, w = img.shape[:2]
        center_x = (w >> 1)
        center_y = (h >> 1)
        sin_angle = np.fabs(np.sin(np.radians(angle)))
        cos_angle = np.fabs(np.cos(np.radians(angle)))
        new_h = int(w * sin_angle + h * cos_angle)
        new_w = int(h * sin_angle + w * cos_angle)

        M = cv2.getRotationMatrix2D((center_x, center_y), angle, 1.0)

        rotated = cv2.warpAffine(img, M, (new_w, new_h))

        return rotated

    def generator_noise_3d(self, img, noise_num):

        h, w, c = img.shape
        size = h * w
        inds_index = np.random.random_integers(0, size - 1, noise_num)
        inds_value = np.random.random_integers(0, 255, noise_num)
        inds_value = inds_value[:, np.newaxis]
        inds_value = np.repeat(inds_value, 3, axis=1)
        img = img.reshape((size, c))
        img[inds_index, :] = img[inds_index, :] + inds_value.reshape((noise_num, 3))
        img = img.reshape((h, w, c))
        np.minimum(img, 255)

        return img

    def generator_noise(self, img, noise_num):

        hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
        v = hsv[:, :, 2]

        def add_noise(img, noise_num):
            h, w = img.shape[:2]
            size = h * w
            inds_index = np.random.random_integers(0, size - 1, noise_num)
            inds_value = np.random.random_integers(0, 255, noise_num)
            img = img.reshape((size, 1))
            img[inds_index, :] = img[inds_index, :] + inds_value.reshape((noise_num, 1))
            img = img.reshape((h, w))
            np.minimum(img, 255)

            return img

        hsv[:, :, 2] = add_noise(v, noise_num)
        img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)

        return img

    def generator_blur(self, img, kernel, sigma):

        # h,w,c = img.shape

        img = cv2.GaussianBlur(img, (kernel, kernel), sigma)

        return img

    def gaussian_lighting_argument(self, img, scale, power, center_x, center_y):
        height, width = img.shape[:2]

        R = np.sqrt(center_x ** 2 + center_y ** 2) * scale
        if 3 == len(img.shape):
            r_idx_array, c_idx_array = np.where(img[:, :, 0] < 256)
            mask_y = r_idx_array.reshape(height, width)
            mask_x = c_idx_array.reshape(height, width)
        else:
            r_idx_array, c_idx_array = np.where(img[:, :] < 256)
            mask_y = r_idx_array.reshape(height, width)
            mask_x = c_idx_array.reshape(height, width)

        # mask_x = repmat(center_x, height, width)
        # mask_y = repmat(center_y, height, width)

        x1 = np.arange(width)
        x_map = repmat(x1, height, 1)

        y1 = np.arange(height)
        y_map = repmat(y1, width, 1)
        y_map = np.transpose(y_map)

        Gauss_map = np.sqrt((x_map - mask_x) ** 2 + (y_map - mask_y) ** 2)

        Gauss_map = np.exp(-0.5 * Gauss_map / R) * power

        if 3 == len(img.shape):
            Gauss_map = Gauss_map[:, :, np.newaxis]
            Gauss_map = np.repeat(Gauss_map, 3, axis=2)

        illumination_img = img * Gauss_map
        illumination_img = np.maximum(np.minimum(illumination_img, 255), 0)

        # if 3 == len(img.shape):
        # illumination_img = normalization3D(illumination_img)
        # else:
        # illumination_img = (illumination_img - np.min(illumination_img) ) / (np.max(illumination_img)
        # \- np.min(illumination_img)) * 255

        # if 3 == len(img.shape):
        # MAX = 255
        # inds = np.where(
        # (illumination_img[:, :, 0] > MAX) &
        # (illumination_img[:, :, 1] > MAX) &
        # (illumination_img[:, :, 2] > MAX) )[0]
        # illumination_img[inds, :] = 255

        # MIN = 0
        # inds = np.where(
        # (illumination_img[:, :, 0] < MIN) &
        # (illumination_img[:, :, 1] < MIN) &
        # (illumination_img[:, :, 2] < MIN) )[0]
        # illumination_img[inds, :] = 0
        # else:
        # MAX = 255
        # inds = np.where(
        # (illumination_img[:, :] > MAX) )[0]
        # illumination_img[inds, :] = 255

        # MIN = 0
        # inds = np.where(
        # (illumination_img[:, :] < MIN) )[0]
        # illumination_img[inds, :] = 0

        illumination_img = np.uint8(illumination_img)

        return illumination_img

    def linear_lighting_argument(self, img, power=1.2, scale=0.4, center=None):
        height, width = img.shape[:2]
        if center is None:
            center = random.randint(0, width), random.randint(0, height)
            # center =1000,1000

        if 3 == len(img.shape):
            r_idx_array, c_idx_array = np.where(img[:, :, 0] < 256)
            r_idx_array = r_idx_array.reshape(height, width)
            c_idx_array = c_idx_array.reshape(height, width)
        else:
            r_idx_array, c_idx_array = np.where(img[:, :] < 256)
            r_idx_array = r_idx_array.reshape(height, width)
            c_idx_array = c_idx_array.reshape(height, width)

        radius = int(math.sqrt(height ** 2 + width ** 2))  #
        distance = np.sqrt((r_idx_array - center[1]) ** 2 + (c_idx_array - center[0]) ** 2)
        scale = max(0, scale)
        brightness = power * (radius - scale * distance) / radius

        if 3 == len(img.shape):
            brightness = brightness[:, :, np.newaxis]
            brightness = np.repeat(brightness, 3, axis=2)

        res_img = img * brightness
        res_img = np.maximum(np.minimum(res_img, 255), 0)
        res_img = np.uint8(res_img)

        return res_img

    def illumination(self, img, scale, center_x, center_y, power, lightscale):
        num = random.randint(0, 2)
        # print num, scale, center_x, center_y, power, lightscale
        num = 0
        if 0 == num:
            return self.gaussian_lighting_argument(img, scale, power, center_x, center_y)
        elif 1 == num:
            return self.linear_lighting_argument(img, power, lightscale, (center_x, center_y))
        else:
            gaussian = self.gaussian_lighting_argument(img, scale, power, center_x, center_y)
            center_x = np.random.randint(500, img.shape[1] - 500)
            center_y = np.random.randint(500, img.shape[0] - 500)
            liner = self.linear_lighting_argument(img, power, lightscale, (center_x, center_y))
            normalization = (gaussian / 2) + (liner / 2)
            return normalization

    def get_distance(self, img, center):
        height, width = img.shape[:2]
        if center is None:
            center = random.randint(0, width), random.randint(0, height)

        if 3 == len(img.shape):
            r_idx_array, c_idx_array = np.where(img[:, :, 0] < 256)
            r_idx_array = r_idx_array.reshape(height, width)
            c_idx_array = c_idx_array.reshape(height, width)
        else:
            r_idx_array, c_idx_array = np.where(img[:, :] < 256)
            r_idx_array = r_idx_array.reshape(height, width)
            c_idx_array = c_idx_array.reshape(height, width)

        distance = np.sqrt((r_idx_array - center[1]) ** 2 + (c_idx_array - center[0]) ** 2)

        return distance

    def get_gauss_map(self, img, center_1, center_2, power, scale):

        distance = self.get_distance(img, center_1)
        radius = int(math.sqrt(center_2[0] ** 2 + center_2[1] ** 2)) * scale  #
        gauss_map = np.exp(-0.5 * distance / radius) * power
        if 3 == len(img.shape):
            gauss_map = gauss_map[:, :, np.newaxis]
            gauss_map = np.repeat(gauss_map, 3, axis=2)

        return img * gauss_map

    def get_linear_map(self, img, center_1, center_2, power, scale):
        distance = self.get_distance(img, center_1)
        radius = int(math.sqrt(center_2[0] ** 2 + center_2[1] ** 2))
        linear_map = power * (radius - distance / (np.exp(scale) - 1)) / radius
        if 3 == len(img.shape):
            linear_map = linear_map[:, :, np.newaxis]
            linear_map = np.repeat(linear_map, 3, axis=2)
        return img * linear_map

    def lighting(self, img, center_1, center_2, power, scale, light_type=None):

        if light_type in ["guass", 0]:
            res_map = self.get_gauss_map(center_1, center_2, power, scale)
        elif light_type in ["linear", 1]:
            res_map = self.get_linear_map(center_1, center_2, power, scale)
        else:
            print("light_type error!")
            return

        if 3 == len(img.shape):
            res_map = res_map[:, :, np.newaxis]
            res_map = np.repeat(res_map, 3, axis=2)

        res_img = img * res_map
        res_img = np.maximum(np.minimum(res_img, 255), 0)
        return res_img

    def light_exchange(self, img):
        # center_x = (img.shape[1] >> 1) + np.random.randint(-10, 10)
        # center_y = (img.shape[0] >> 1) + np.random.randint(-10, 10)
        center_x = 10
        center_y = 10
        center_1 = (center_x, center_y)
        scale = random.uniform(1, 5)
        power = random.uniform(0.5, 1.1)
        # center_x = (img.shape[1] >> 1) + np.random.randint(-10, 10)
        # center_y = (img.shape[0] >> 1) + np.random.randint(-10, 10)
        center_x = img.shape[1]
        center_y = img.shape[0]
        center_2 = (center_x, center_y)
        # illumination_img = Get_Linear_map(img, center_1, center_2, power, scale)
        select_num = np.random.randint(0, 1)
        if 1 == select_num:
            illumination_img = self.get_gauss_map(img, center_1, center_2, power, scale)
        elif 0 == select_num:
            illumination_img = self.get_linear_map(img, center_1, center_2, power, scale)
        else:
            illumination_img_1 = self.get_gauss_map(img, center_1, center_2, power, scale)
            illumination_img_2 = self.get_linear_map(img, center_1, center_2, power, scale)
            illumination_img = (illumination_img_1 >> 1) + (illumination_img_2 >> 1)

        return illumination_img


class WarpMLS:
    def __init__(self, src, src_pts, dst_pts, dst_w, dst_h, trans_ratio=1.):
        self.src = src
        self.src_pts = src_pts
        self.dst_pts = dst_pts
        self.pt_count = len(self.dst_pts)
        self.dst_w = dst_w
        self.dst_h = dst_h
        self.trans_ratio = trans_ratio
        self.grid_size = 100
        self.rdx = np.zeros((self.dst_h, self.dst_w))
        self.rdy = np.zeros((self.dst_h, self.dst_w))

    @staticmethod
    def __bilinear_interp(x, y, v11, v12, v21, v22):
        return (v11 * (1 - y) + v12 * y) * (1 - x) + (v21 * (1 - y) + v22 * y) * x

    def generate(self):
        self.calc_delta()
        return self.gen_img()

    def calc_delta(self):
        w = np.zeros(self.pt_count, dtype=np.float32)

        if self.pt_count < 2:
            return

        i = 0
        while 1:
            if self.dst_w <= i < self.dst_w + self.grid_size - 1:
                i = self.dst_w - 1
            elif i >= self.dst_w:
                break

            j = 0
            while 1:
                if self.dst_h <= j < self.dst_h + self.grid_size - 1:
                    j = self.dst_h - 1
                elif j >= self.dst_h:
                    break

                sw = 0
                swp = np.zeros(2, dtype=np.float32)
                swq = np.zeros(2, dtype=np.float32)
                new_pt = np.zeros(2, dtype=np.float32)
                cur_pt = np.array([i, j], dtype=np.float32)

                k = 0
                for k in range(self.pt_count):
                    if i == self.dst_pts[k][0] and j == self.dst_pts[k][1]:
                        break

                    w[k] = 1. / ((i - self.dst_pts[k][0]) * (i - self.dst_pts[k][0]) +
                                 (j - self.dst_pts[k][1]) * (j - self.dst_pts[k][1]))

                    sw += w[k]
                    swp = swp + w[k] * np.array(self.dst_pts[k])
                    swq = swq + w[k] * np.array(self.src_pts[k])

                if k == self.pt_count - 1:
                    pstar = 1 / sw * swp
                    qstar = 1 / sw * swq

                    miu_s = 0
                    for k in range(self.pt_count):
                        if i == self.dst_pts[k][0] and j == self.dst_pts[k][1]:
                            continue
                        pt_i = self.dst_pts[k] - pstar
                        miu_s += w[k] * np.sum(pt_i * pt_i)

                    cur_pt -= pstar
                    cur_pt_j = np.array([-cur_pt[1], cur_pt[0]])

                    for k in range(self.pt_count):
                        if i == self.dst_pts[k][0] and j == self.dst_pts[k][1]:
                            continue

                        pt_i = self.dst_pts[k] - pstar
                        pt_j = np.array([-pt_i[1], pt_i[0]])

                        tmp_pt = np.zeros(2, dtype=np.float32)
                        tmp_pt[0] = np.sum(pt_i * cur_pt) * self.src_pts[k][0] - \
                                    np.sum(pt_j * cur_pt) * self.src_pts[k][1]
                        tmp_pt[1] = -np.sum(pt_i * cur_pt_j) * self.src_pts[k][0] + \
                                    np.sum(pt_j * cur_pt_j) * self.src_pts[k][1]
                        tmp_pt *= (w[k] / miu_s)
                        new_pt += tmp_pt

                    new_pt += qstar
                else:
                    new_pt = self.src_pts[k]

                self.rdx[j, i] = new_pt[0] - i
                self.rdy[j, i] = new_pt[1] - j

                j += self.grid_size
            i += self.grid_size

    def gen_img(self):
        src_h, src_w = self.src.shape[:2]
        dst = np.zeros_like(self.src, dtype=np.float32)

        for i in np.arange(0, self.dst_h, self.grid_size):
            for j in np.arange(0, self.dst_w, self.grid_size):
                ni = i + self.grid_size
                nj = j + self.grid_size
                w = h = self.grid_size
                if ni >= self.dst_h:
                    ni = self.dst_h - 1
                    h = ni - i + 1
                if nj >= self.dst_w:
                    nj = self.dst_w - 1
                    w = nj - j + 1

                di = np.reshape(np.arange(h), (-1, 1))
                dj = np.reshape(np.arange(w), (1, -1))
                delta_x = self.__bilinear_interp(di / h, dj / w,
                                                 self.rdx[i, j], self.rdx[i, nj],
                                                 self.rdx[ni, j], self.rdx[ni, nj])
                delta_y = self.__bilinear_interp(di / h, dj / w,
                                                 self.rdy[i, j], self.rdy[i, nj],
                                                 self.rdy[ni, j], self.rdy[ni, nj])
                nx = j + dj + delta_x * self.trans_ratio
                ny = i + di + delta_y * self.trans_ratio
                nx = np.clip(nx, 0, src_w - 1)
                ny = np.clip(ny, 0, src_h - 1)
                nxi = np.array(np.floor(nx), dtype=np.int32)
                nyi = np.array(np.floor(ny), dtype=np.int32)
                nxi1 = np.array(np.ceil(nx), dtype=np.int32)
                nyi1 = np.array(np.ceil(ny), dtype=np.int32)

                if len(self.src.shape) == 3:
                    x = np.tile(np.expand_dims(ny - nyi, axis=-1), (1, 1, 3))
                    y = np.tile(np.expand_dims(nx - nxi, axis=-1), (1, 1, 3))
                else:
                    x = ny - nyi
                    y = nx - nxi
                dst[i:i + h, j:j + w] = self.__bilinear_interp(x,
                                                               y,
                                                               self.src[nyi, nxi],
                                                               self.src[nyi, nxi1],
                                                               self.src[nyi1, nxi],
                                                               self.src[nyi1, nxi1]
                                                               )

        dst = np.clip(dst, 0, 255)
        dst = np.array(dst, dtype=np.uint8)

        return dst


# 数据增强
class Augment():
    def __init__(self):
        self.a = 0

    def _crop(self, imgs):
        crop = random.uniform(0, 0.1)
        for i in range(len(imgs)):
            imgs[i] = imgs[i].crop(
                [0 + imgs[i].size[0] * crop, 0 + imgs[i].size[1] * crop, imgs[i].size[0] * (1 - crop),
                 imgs[i].size[1] * (1 - crop)])  # 裁剪
        return imgs

    def _resize(self, imgs):
        x = np.random.randint(imgs[0].size[0] * 0.5, imgs[0].size[0] * 1.5)
        y = np.random.randint(imgs[0].size[1] * 0.5, imgs[0].size[1] * 1.5)
        for i in range(len(imgs)):
            imgs[i] = imgs[i].resize((x, y))  # 对比度增强
        return imgs

    def _rotate(self, imgs):
        param = random.uniform(-360, 360)
        for i in range(len(imgs)):
            aa = imgs[i].copy()
            bb= aa.rotate(param)
#             print('------->',bb.size,aa.size)
            assert bb.size == aa.size
            imgs[i] = imgs[i].rotate(param)  # 随机旋转一定角度（角度范围-0.15，0.15）
        return imgs

    def _gauss(self, img):
        img = img.filter(ImageFilter.GaussianBlur(radius=random.uniform(0, 1.2)))  # 高斯模糊，0-2之间
        return img

    def _Brightness(self, img):
        img = ImageEnhance.Brightness(img).enhance(random.uniform(0.5, 1))  # 亮度增强
        return img

    def _Contrast(self, img):
        img = ImageEnhance.Contrast(img).enhance(random.uniform(0.4, 2))  # 对比度增强
        return img

    def _Sharpness(self, img):
        img = ImageEnhance.Sharpness(img).enhance(random.uniform(0.5, 3))  # 锐度增强
        return img

    def _distort(self, img):
        img = np.asarray(img)
        segment = 4
        img_h, img_w = img.shape[:2]

        cut = img_w // segment
        thresh = cut // 8
        if thresh == 0:
            thresh = 1
        # thresh = img_h // segment // 3
        # thresh = img_h // 5

        src_pts = list()
        dst_pts = list()

        src_pts.append([0, 0])
        src_pts.append([img_w, 0])
        src_pts.append([img_w, img_h])
        src_pts.append([0, img_h])

        dst_pts.append([np.random.randint(thresh), np.random.randint(thresh)])
        dst_pts.append([img_w - np.random.randint(thresh), np.random.randint(thresh)])
        dst_pts.append([img_w - np.random.randint(thresh), img_h - np.random.randint(thresh)])
        dst_pts.append([np.random.randint(thresh), img_h - np.random.randint(thresh)])

        half_thresh = thresh * 0.5

        for cut_idx in np.arange(1, segment, 1):
            src_pts.append([cut * cut_idx, 0])
            src_pts.append([cut * cut_idx, img_h])
            dst_pts.append([cut * cut_idx + np.random.randint(thresh) - half_thresh,
                            np.random.randint(thresh) - half_thresh])
            dst_pts.append([cut * cut_idx + np.random.randint(thresh) - half_thresh,
                            img_h + np.random.randint(thresh) - half_thresh])

        trans = WarpMLS(img, src_pts, dst_pts, img_w, img_h)
        dst = trans.generate()
        dst = Image.fromarray(dst)
        return dst

    def _stretch(self, img):
        img = np.asarray(img)
        segment = 4
        img_h, img_w = img.shape[:2]

        cut = img_w // segment
        thresh = cut * 4 // 5
        if thresh == 0:
            thresh = 1
        # thresh = img_h // segment // 3
        # thresh = img_h // 5

        src_pts = list()
        dst_pts = list()

        src_pts.append([0, 0])
        src_pts.append([img_w, 0])
        src_pts.append([img_w, img_h])
        src_pts.append([0, img_h])

        dst_pts.append([0, 0])
        dst_pts.append([img_w, 0])
        dst_pts.append([img_w, img_h])
        dst_pts.append([0, img_h])

        half_thresh = thresh * 0.5

        for cut_idx in np.arange(1, segment, 1):
            move = np.random.randint(thresh) - half_thresh
            src_pts.append([cut * cut_idx, 0])
            src_pts.append([cut * cut_idx, img_h])
            dst_pts.append([cut * cut_idx + move, 0])
            dst_pts.append([cut * cut_idx + move, img_h])

        trans = WarpMLS(img, src_pts, dst_pts, img_w, img_h)
        dst = trans.generate()
        dst = Image.fromarray(dst)
        return dst

    def _perspective(self, img):
        img = np.asarray(img)
        img_h, img_w = img.shape[:2]

        thresh = img_h // 8
        if thresh == 0:
            thresh = 1

        src_pts = list()
        dst_pts = list()

        src_pts.append([0, 0])
        src_pts.append([img_w, 0])
        src_pts.append([img_w, img_h])
        src_pts.append([0, img_h])

        dst_pts.append([0, np.random.randint(thresh)])
        dst_pts.append([img_w, np.random.randint(thresh)])
        dst_pts.append([img_w, img_h - np.random.randint(thresh)])
        dst_pts.append([0, img_h - np.random.randint(thresh)])

        trans = WarpMLS(img, src_pts, dst_pts, img_w, img_h)
        dst = trans.generate()
        dst = Image.fromarray(dst)
        return dst

    def randomfunction(self, img1, img2):
        rand_num = random.uniform(0, 1)
        if rand_num < 1:
            rand_list = ['self._rotate', 'self._gauss', 'self._Brightness',
                         'self._Contrast', 'self._Sharpness']
            rand_list = random.sample(rand_list, random.randint(1, 5))
            for str in rand_list:
                if str == 'self._rotate' or str == 'self._crop' or str == 'self._resize':
                    img = [img1, img2]
                    img = eval(str)(img)
                    source_img = img[0]
                    label_img = img[1]
                else:
                    img = img1
                    source_img = eval(str)(img)
                    label_img = img2
        else:
            source_img, label_img = img1, img2
        return source_img, label_img

def function(sourceimg_name,labelimg_name):
    label_im = cv2.imread(labelimg_name)
    source_im = cv2.imread(sourceimg_name)
    image_source_im = Image.fromarray(cv2.cvtColor(source_im, cv2.COLOR_BGR2RGB))
    image_label_im = Image.fromarray(label_im)
    rand_num = random.uniform(0, 1)
    if rand_num < 0.5:
        new_im = augbright.light_exchange(source_im)
        new_label_im = label_im
    else:
        new_im, new_label_im = augment.randomfunction(image_source_im, image_label_im)
        new_im = cv2.cvtColor(np.asarray(new_im), cv2.COLOR_RGB2BGR)
        new_label_im = np.asarray(new_label_im)
    return new_im,new_label_im

if __name__ == "__main__":
    # image_dir = '/mnt/data/ocr_data/table_data/contract_bank_merge_860_860_v1'
    image_dir = r'D:\Projects_data\table\contract\contract_bank_merge_860_860_v1'
    save_dir = '../contract_bank_merge_860_860_aug_v1'
    img_lst = glob.glob(image_dir + '/*.*g')
#     img_lst2 = glob.glob(image_dir + '/*.png')
#     img_lst.extend(img_lst2)
    augbright = AugmentBright()
    augment = Augment()
    a = 0
    try:
        for im_name in img_lst:
            print('----->:',a,len(img_lst))
            a+=1
            if '-label' not in im_name:
                file_path = os.path.dirname(im_name)
                file_name = os.path.basename(im_name)
                sourceimg_name = file_name
                labelimg_name = sourceimg_name.split('.')[0] + '-label.jpg'
                label_im = cv2.imread(file_path + '/' + labelimg_name)
                source_im = cv2.imread(file_path + '/' + sourceimg_name)
                image_source_im = Image.fromarray(cv2.cvtColor(source_im, cv2.COLOR_BGR2RGB))
                image_label_im = Image.fromarray(label_im)
                for index in range(20):
                    rand_num = random.uniform(0, 1)
                    if rand_num < 0.5:
                        new_im = augbright.light_exchange(source_im)
                        new_label_im = label_im
                    else:
                        new_im, new_label_im = augment.randomfunction(image_source_im, image_label_im)
                        new_im = cv2.cvtColor(np.asarray(new_im), cv2.COLOR_RGB2BGR)
                        new_label_im = np.asarray(new_label_im)
                    source_new_name = os.path.join(save_dir, sourceimg_name.split('.')[0] + '_' + str(index) + '.jpg')
                    label_new_name = os.path.join(save_dir, sourceimg_name.split('.')[0] + '_' + str(index) + '-label.jpg')
#                     new_im = cv2.resize(new_im, (1024, 640))
#                     new_label_im = cv2.resize(new_label_im, (1024, 640))
                    cv2.imwrite(source_new_name, new_im)
                    cv2.imwrite(label_new_name, new_label_im)
    except:
        pass
    print('----->finfish')
